package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 添加联系人
     *  1.记录到探花数据库
     *  2.将好友关系注册到环信
     */
    public void contacts(Long friendId) {
        Long userId = UserHolder.getUserId();
        //将好友关系记录到探花数据库
        friendApi.save(userId,friendId);
        //将好友关系注册到环信
        huanXinTemplate.addContact("hx"+userId,"hx"+friendId);
    }

    //查询联系人
    public PageResult findContacts(Integer page, Integer pagesize) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用API查询联系人  -- List<Friend>
        List<Friend> list = friendApi.findByUserId(userId,page,pagesize);
        //3、判断列表是否为空
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //提取所有的好友id
        List<Long> friendIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //一次性查询所有的好友信息，构造map
        Map<Long, UserInfo> map = userInfoApi.findByIds(friendIds);
        //4、一个Friend构造一个Vo
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            //获取好友的id
            Long friendId = friend.getFriendId();
            //查询好友的用户信息UserInfo
            UserInfo userInfo = map.get(friendId);   //远程调用查询用户信息
            ContactVo vo = ContactVo.init(userInfo);
            vos.add(vo);
        }
        //5、返回
        return new PageResult(page,pagesize,0l,vos);
    }
}
